using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using Ninject;

namespace Sample1.Web.Models
{
    public class ProductRepository : IProductRepository
    {
        private readonly Sample1WebContext _context;

        [Inject]
        public ProductRepository(Sample1WebContext context)
        {
            this._context = context;
        }

        public IEnumerable<Product> GetAllProducts(params Expression<Func<Product, object>>[] includeProperties)
        {
            IQueryable<Product> query = _context.Products;
            foreach (var includeProperty in includeProperties)
            {
                query = query.Include(includeProperty);
            }
            
            return query.ToList();
        }

        public Product GetById(int id)
        {
            return _context.Products.Find(id);
        }

        public bool Contains(string name)
        {
            return this._context.Products.FirstOrDefault(p => p.Name.Equals(name, StringComparison.CurrentCultureIgnoreCase)) != null;
        }

        public bool Contains(string name, int excludeId)
        {
            return this._context.Products.FirstOrDefault(p => p.ProductId != excludeId && p.Name.Equals(name, StringComparison.CurrentCultureIgnoreCase)) != null;
        }

        public void InsertOrUpdate(Product product)
        {
            if (product.ProductId == 0)
            {
                // New entity
                _context.Products.Add(product);
            }
            else
            {
                // Existing entity
                _context.Products.Attach(product);
                _context.Entry(product).State = EntityState.Modified;
            }
        }

        public void Delete(int id)
        {
            var product = _context.Products.Find(id);
            _context.Products.Remove(product);
        }

        public void Save()
        {
            _context.SaveChanges();
        }
    }

    public interface IProductRepository
    {
        IEnumerable<Product> GetAllProducts(params Expression<Func<Product, object>>[] includeProperties);
        Product GetById(int id);
        bool Contains(string name);
        bool Contains(string name, int excludeId);
        void InsertOrUpdate(Product product);
        void Delete(int id);
        void Save();
    }
}